#!/bin/bash

# Get the absolute path of the current script
DIR="$( cd "$( dirname "$0"  )" && pwd  )"

# Define a new variable to represent the parent directory
PARENT_DIR="${DIR}/.."

# Assemble Classpath
CLASSPATH="${PARENT_DIR}/lib/*:${PARENT_DIR}/java-example-starter.jar:${PARENT_DIR}/java-example-starter-sources.jar"

# Set the path of the log4j2 configuration file
LOG4J2_CONFIG="${PARENT_DIR}/conf/log4j2.xml"

# memory config

LIMIT_BYTES=$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes)

if [[ ${LIMIT_BYTES} -le 1073741824 ]]; then
  JVM_HEAP_SIZE="512M"
  JVM_META_SIZE="128M"
  JVM_MAX_META_SIZE="256M"
  JVM_DIRECT_MEM_SIZE="64M"
  JVM_THREAD_STACK_SIZE="512K"
elif [[ ${LIMIT_BYTES} -le 2147483648 ]]; then
  JVM_HEAP_SIZE="1G"
  JVM_META_SIZE="128M"
  JVM_MAX_META_SIZE="256M"
  JVM_DIRECT_MEM_SIZE="512M"
  JVM_THREAD_STACK_SIZE="512K"
elif [[ ${LIMIT_BYTES} -le 4294967296 ]]; then
  JVM_HEAP_SIZE="2G"
  JVM_META_SIZE="128M"
  JVM_MAX_META_SIZE="256M"
  JVM_DIRECT_MEM_SIZE="5122M"
  JVM_THREAD_STACK_SIZE="512K"
else
  JVM_HEAP_SIZE="4G"
  JVM_META_SIZE="256M"
  JVM_MAX_META_SIZE="512M"
  JVM_DIRECT_MEM_SIZE="1G"
  JVM_THREAD_STACK_SIZE="512K"
fi

# Set the JVM options

if [[ -n ${JVM_HEAP_SIZE} ]]; then
  JVM_OPT="${JVM_OPT} -Xms${JVM_HEAP_SIZE} -Xmx${JVM_HEAP_SIZE}"
fi

if [[ -n ${JVM_META_SIZE} ]]; then
  JVM_OPT="${JVM_OPT} -XX:MetaspaceSize=${JVM_META_SIZE}"
fi

if [[ -n ${JVM_MAX_META_SIZE} ]]; then
  JVM_OPT="${JVM_OPT} -XX:MaxMetaspaceSize=${JVM_MAX_META_SIZE}"
fi

if [[ -n ${JVM_DIRECT_MEM_SIZE} ]]; then
  JVM_OPT="${JVM_OPT} -XX:MaxDirectMemorySize=${JVM_DIRECT_MEM_SIZE}"
fi

if [[ -n ${JVM_THREAD_STACK_SIZE} ]]; then
  JVM_OPT="${JVM_OPT} -Xss${JVM_THREAD_STACK_SIZE}"
fi

# Launch the Java application
java ${JVM_OPT} -Dlog4j.configurationFile=${LOG4J2_CONFIG} -cp ${CLASSPATH} com.shoothzj.example.starter.Main
